package com.ala4.oxcafe.repository;

import com.ala4.oxcafe.common.utils.collection.CollUtil;
import com.ala4.oxcafe.entity.RoleInfo;
import com.ala4.oxcafe.entity.UserRoleRel;
import com.ala4.oxcafe.exception.BusinessException;
import com.ala4.oxcafe.repository.mapper.UserRoleRelMapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户角色关联表
 *
 * @author PING
 * @date 2025-03-25
 */
@Repository
public class UserRoleRelRepository extends ServiceImpl<UserRoleRelMapper, UserRoleRel> implements IService<UserRoleRel> {


    public void createUserRoleRel(Long userId, List<Long> roleIds) {

        if (CollUtil.isNotEmpty(roleIds)) {
            List<UserRoleRel> userRoleRelList = CollUtil.newArrayList();
            for (Long roleId : roleIds) {
                userRoleRelList.add(new UserRoleRel(userId, roleId));
            }
            // 保存用户角色信息
            this.saveBatch(userRoleRelList);
        }
    }

    public Map<Long, List<RoleInfo>> selectUserRole(Set<Long> userIds) {
        if (CollUtil.isEmpty(userIds)) {
            throw new BusinessException("userId不能为空");
        }
        List<RoleInfo> roleInfos = this.baseMapper.selectUserRole(userIds);
        return roleInfos.stream().collect(Collectors.groupingBy(RoleInfo::getUserId));
    }

    public List<RoleInfo> selectUserRole(Long userId) {
        return this.baseMapper.selectUserRole(CollUtil.newHashSet(userId));
    }
}
